package com.itboye.lottery.activity.follow;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ObservableScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.itboye.bylibrary.util.ScreenUtil;
import com.itboye.bylibrary.widget.glide.GlideUtil;
import com.itboye.lottery.base.BaseActivity;
import com.itboye.lottery.R;
import com.itboye.lottery.adapter.CommonPagerAdapter;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.bean.HotPeoleDetail;
import com.itboye.lottery.fragment.gendan.HongRenOrderListFragment;
import com.itboye.lottery.presenter.UserPresenter;
import com.itboye.lottery.retrofit.ResponseCallback;
import com.itboye.lottery.view.frag_vp_frag.PersonalViewpager;
import com.itboye.lottery.view.rounded.RoundedImageView;

import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.BindViews;

/**
 * 这里是个人购买的记录介绍
 */
public class HotPeopleInfoActivity extends BaseActivity implements ResponseCallback {


    @BindView(R.id.iv_user_icon)
    ImageView mIvUserIcon;


    @BindView(R.id.iv_user_rank)
    ImageView mIvUserRank;

    @BindView(R.id.tv_nickname)
    TextView mTvNickname;
    @BindView(R.id.tv_fans)
    TextView mTvFans;
    @BindView(R.id.tv_win_total_money)
    TextView mTvWinTotalMoney;
    @BindView(R.id.tv_unit_award)
    TextView mTvUnitAward;
    TextView tv_seven_day_award;
    @BindView(R.id.tv_thirty_day_award)
    TextView mTvThirtyDayAward;
    @BindView(R.id.tv_value)
    TextView mTvValue;

    @BindViews({R.id.iv_term_one,
            R.id.iv_term_two,
            R.id.iv_term_three,
            R.id.iv_term_four,
            R.id.iv_term_five,})
    ImageView[] mIvTermImgs;
    ImageView iv_term_one;
    ImageView iv_term_two;
    ImageView iv_term_three;
    ImageView iv_term_four;
    ImageView iv_term_five;
    //关注
    @BindView(R.id.ll_follow)
    LinearLayout mLlFollow;

//    @BindView(R.id.tv_follow_statue)
//    TextView mTvFollowStatue;

//    @BindView(R.id.tv_custom_order)
//    TextView mTvCustomOrder;

    @BindView(R.id.jilu)
    TextView jilu;
    //定制跟单；
    @BindView(R.id.ll_custom_follow)
    LinearLayout mLlCustomFollow;

    //    @BindView(R.id.scrollView_main)
    public ObservableScrollView scrollView_main;

    public static final String HOT_PEOPLE_ID = "userId";
    @BindView(R.id.vp_gendan_hot_people_detail)
    PersonalViewpager vp_gendan_hot_people_detail;
    @BindView(R.id.tl_gendan_hot_people_detail)
    TabLayout tl_gendan_hot_people_detail;

    @BindView(R.id.tl_gendan_hot_people_detail2)
    TabLayout tl_gendan_hot_people_detail2;

    LinearLayout lay_transroot;

    @BindView(R.id.tv_hotpeople_daihong)
    TextView tv_hotpeople_daihong;

    @BindView(R.id.tv_hotpeople_yingli)
    TextView tv_hotpeople_yingli;
    @BindView(R.id.tv_total_bonus)
    TextView tv_total_bonus;
    @BindView(R.id.tv_guanzhu)
    TextView tv_guanzhu;
    TextView tv_fans;
    //    private PullToRefreshListView mRefreshListView;
//    private ListView mListView;
//    private HotPeopleInfoAdapter mHotPeopleInfoAdapter;
//    private ResHotPeopleInfo mResHotPeopleInfo;
    private String mHotPeopleId;
    ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
    private int statusBarHeight;
    private int topLayoutHeight;
    private int maxDiff = 0;
    UserPresenter userPresenter = new UserPresenter(this);
    private HotPeoleDetail hotPeoleDetail = new HotPeoleDetail();
    private int position = 0;

    TextView tv_attention;
    RelativeLayout rl_attention;

    @Override
    protected void initData() {
        setTitle("红人详情");
        mIvTermImgs = new ImageView[]{iv_term_one, iv_term_two, iv_term_three, iv_term_four, iv_term_five};
        mHotPeopleId = getIntent().getStringExtra(HOT_PEOPLE_ID);
//        statusBarHeight = ScreenUtil.getStatusBarHeight(getApplicationContext());
        topLayoutHeight = ScreenUtil.getMeasureHeight(lay_transroot);
//        mHotPeopleInfoAdapter = new HotPeopleInfoAdapter();
//        mRefreshListView.setAdapter(mHotPeopleInfoAdapter);
        requestData();

    }

    boolean hasInit = false;

    private void initFragment() {
        if (!hasInit) {
            fragmentArrayList.add(HongRenOrderListFragment.newInstance(0, mHotPeopleId, hotPeoleDetail.getPlan_info()));
            fragmentArrayList.add(HongRenOrderListFragment.newInstance(5, mHotPeopleId,new ArrayList<>()));
            fragmentArrayList.add(HongRenOrderListFragment.newInstance(6, mHotPeopleId, new ArrayList<>()));
            fragmentArrayList.add(HongRenOrderListFragment.newInstance(99, mHotPeopleId, new ArrayList<>()));
            vp_gendan_hot_people_detail.setAdapter(new CommonPagerAdapter(this, fragmentArrayList, R.array.follow_title, getSupportFragmentManager()));
            vp_gendan_hot_people_detail.setOffscreenPageLimit(5);
            tl_gendan_hot_people_detail.setupWithViewPager(vp_gendan_hot_people_detail);
            tl_gendan_hot_people_detail2.setupWithViewPager(vp_gendan_hot_people_detail);
            vp_gendan_hot_people_detail.setCurrentItem(getIntent().getIntExtra("order_position", 0), false);

            vp_gendan_hot_people_detail.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
//                switch (position) {
//                    case 0:
//                         break;
//                    case 1:
//                        break;
//                    case 2:
//                        break;
//                    case 3:
//                        break;
//                }
                    type = position + 1;
                    requestData();
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            vp_gendan_hot_people_detail.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    HotPeopleInfoActivity.this.position = position;
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            initScrollViewListener();
            hasInit = true;
        } else {
            pull_to_refresh_scrollView.onRefreshComplete();
            ((HongRenOrderListFragment) fragmentArrayList.get(position)).setData(hotPeoleDetail.getPlan_info());
        }
    }

    PullToRefreshScrollView pull_to_refresh_scrollView;

    private void initScrollViewListener() {
        pull_to_refresh_scrollView.setMode(PullToRefreshBase.Mode.BOTH);
        pull_to_refresh_scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ObservableScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ObservableScrollView> refreshView) {
                ((HongRenOrderListFragment) fragmentArrayList.get(position)).page = 1;
                requestData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ObservableScrollView> refreshView) {
                ((HongRenOrderListFragment) fragmentArrayList.get(position)).page++;
                requestData();
            }
        });
        scrollView_main = pull_to_refresh_scrollView.getRefreshableView();
        scrollView_main.setScrollViewListener((scrollView, x, y, oldx, oldy) -> {
            //悬停tab
            int[] location = new int[2];
            tl_gendan_hot_people_detail.getLocationOnScreen(location);
            int yPosition = location[1];
            int visibleY = statusBarHeight + topLayoutHeight;
            Log.v("params", statusBarHeight + ">>" + topLayoutHeight + "  yPosition" + yPosition);

            if (yPosition <= visibleY) {
                tl_gendan_hot_people_detail.setVisibility(View.INVISIBLE);
                tl_gendan_hot_people_detail2.setVisibility(View.VISIBLE);
            } else {
                tl_gendan_hot_people_detail2.setVisibility(View.GONE);
                tl_gendan_hot_people_detail.setVisibility(View.VISIBLE);
            }
            if (yPosition - visibleY > maxDiff) {//获取最大间距
                maxDiff = yPosition - visibleY;
            }
//            PluLog.i("LHD PersonalCenterActivity    y = $yPosition   maxDiff = $maxDiff")
            //tab 渐变
            if (maxDiff <= 0) return;
            int diff = yPosition - visibleY;
            DecimalFormat df = new DecimalFormat("0.0");
//            PluLog.i("LHD  距离 = $diff  maxDiff = $maxDiff" + "   比例 = " + df.format(diff * 255 / maxDiff) + "  最终值 = " + df.format(diff * 255 / maxDiff))
            if (diff >= 0) {
                String valueLong = df.format(diff * 255 / maxDiff);
                String value = valueLong.substring(0, valueLong.length() - 2);
//                PluLog.i("LHD 最终透明值 ： $value")
                int alph = 255 - Integer.parseInt(value);
//                PluLog.i("LHD  透明值 = $alph    $value")
//                    relaTop.setBackgroundColor(Color.argb(alph, 47, 48, 47));
            } else {
//                    relaTop.setBackgroundColor(Color.argb(255, 47, 48, 47));
            }

            //上拉加载
            if (y == (scrollView.getChildAt(0).getMeasuredHeight() - scrollView.getMeasuredHeight())) {
                Log.i("LHD", "LHHD >>>>>>>>>>>>>  滑动到底部");
//                    ((GenDanHongRenDetailFragment)fragmentArrayList.get(vp_gendan_hot_people_detail.getCurrentItem())).loadMore();
//                    fragmentOne.loadMore();
            }
        });
    }

    public void requestData() {
        requestHeader(mHotPeopleId);
//        requestHotOrder(hotPeopleId);
    }


    int type = 1, size = 10;

    private void requestHeader(String hotPeopleId) {
        try {
            showDialog("数据请求中");
            userPresenter.getHotPeopleDetail(hotPeopleId, type, ((HongRenOrderListFragment) fragmentArrayList.get(position)).page, size);
        } catch (Exception e) {
            userPresenter.getHotPeopleDetail(hotPeopleId, type, 1, size);
        }
    }

    /**
     * 这里我们是用来刷新头部的数据的
     */
    RoundedImageView iv_user_icon;
    TextView tv_nickname;

    private void updateHeader() {
        if (hotPeoleDetail.getU_info() != null) {
            tv_nickname.setText(hotPeoleDetail.getU_info().getNickname());
            GlideUtil.displayForCircle(this, hotPeoleDetail.getU_info().getHead_pic(),R.mipmap.head_default, iv_user_icon);
        }
        try {
            tv_hotpeople_daihong.setText((hotPeoleDetail.getRed_people_num() == null ? 0 : hotPeoleDetail.getRed_people_num().getRed_num()) + "人");//累计带红人数
            tv_hotpeople_yingli.setText(hotPeoleDetail.getEarn_rate() == null ? "0.00%" : String.format("%.2f", Double.parseDouble(hotPeoleDetail.getEarn_rate())) + "%");//盈利率
            if (hotPeoleDetail.getAll_plan_num()<=0) {
                tv_seven_day_award.setText("0%");//命中率
            }else{
                tv_seven_day_award.setText(String.format("%.2f",(double) (hotPeoleDetail.getHit_number()) / hotPeoleDetail.getAll_plan_num() * 100) + "%");//命中率
            }
            tv_total_bonus.setText(hotPeoleDetail.getRed_people_num() == null ? "0元" : String.format("%.2f",Double.parseDouble(hotPeoleDetail.getRed_people_num().getWin_amount())) + "元");//累计奖金
            tv_guanzhu.setText("关注:" + hotPeoleDetail.getFollow_num());
            tv_fans.setText("粉丝:" + hotPeoleDetail.getFollowed_num());
            //近5期的状况；
            for (int i = 0; i < mIvTermImgs.length; i++) {
                if (hotPeoleDetail.getFive_game_hit() != null) {
                    if (i < hotPeoleDetail.getFive_game_hit().size()) {
                        if (hotPeoleDetail.getFive_game_hit().get(i).equals("0")) {
                            mIvTermImgs[i].setImageResource(R.mipmap.weizhong);
                        } else {
                            mIvTermImgs[i].setImageResource(R.mipmap.zhong);
                        }
                    } else {
                        mIvTermImgs[i].setVisibility(View.INVISIBLE);
                    }
                }

            }
            if (TextUtils.isEmpty(hotPeoleDetail.getAll_plan_hit_num())) {//红单记录
                jilu.setVisibility(View.GONE);
            } else {
                jilu.setText(hotPeoleDetail.getAll_plan_hit_num());
                jilu.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static Intent getIntent(Context context, String hotPeopleId) {
        Intent intent = new Intent(context, HotPeopleInfoActivity.class);
        intent.putExtra(HOT_PEOPLE_ID, hotPeopleId);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_hot_people_info;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_attention:
                //关注取消关注
                if (hotPeoleDetail.getIs_follow() == 0) {
                    userPresenter.follow(Integer.valueOf(mHotPeopleId), 1);
                } else {
                    userPresenter.follow(Integer.valueOf(mHotPeopleId), 2);
                }
                break;
        }
    }

    @Override
    public void success(@NotNull Object o, @NotNull String requestSuccessType) {
        pull_to_refresh_scrollView.onRefreshComplete();
        dissDialog();
        if (requestSuccessType == userPresenter.getHotPeopleDetail_SUCCESS) {
            hotPeoleDetail = (HotPeoleDetail) o;
            if (hotPeoleDetail != null) {
                updateHeader();
                initFragment();
                setIsFollow();
            }
        } else if (requestSuccessType == userPresenter.follow_SUCCESS) {
            if (hotPeoleDetail.getIs_follow() == 0) {
                hotPeoleDetail.setIs_follow(1);
            } else {
                hotPeoleDetail.setIs_follow(0);
            }
            setIsFollow();
        }
    }

    private void setIsFollow() {
        if (hotPeoleDetail.getIs_follow() == 0) {
            tv_attention.setText("关注");
            tv_attention.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.weiguanzhu, 0, 0, 0);
            rl_attention.setBackgroundResource(R.mipmap.ditu);
            tv_attention.setTextColor(getResources().getColor(R.color.white));
        } else {
            tv_attention.setText("已关注");
            tv_attention.setTextColor(getResources().getColor(R.color.red));
            tv_attention.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.yiguanzhu, 0, 0, 0);
            rl_attention.setBackgroundResource(R.mipmap.ditu2);
        }
    }

    @Override
    public void fail(int code, @NotNull Object msg, @NotNull String requestErrorType) {
        dissDialog();
        pull_to_refresh_scrollView.onRefreshComplete();
        if (requestErrorType == userPresenter.getHotPeopleDetail_FAIL) {
            ByAlert.alert(msg);
            pull_to_refresh_scrollView.onRefreshComplete();
        }
        if (requestErrorType == userPresenter.follow_FAIL) {
            ByAlert.alert(msg);
        }
    }
}
